<!--
 @description 客户详情
 @fileName index.vue
 @author zengqiongying
 @created 2022/11/06 14:23:52
-->
<template>
  <div class="customer-detail-page bg_white">
    <div class="detail-headers">
      <ComHeader
        id="oHeader"
        fixed
        title="客户详情"
        show-statusbar
        white-font
        :border="barOpacity===1"
        :bg-color="headerBgColor"
        @get-height="handleHeadHeight"
      />
      <div class="detail-basic-box">
        <div class="basic-wrapper">
          <div class="u-head">
            <div class="u-avatar">
              <ImageVideo lazy-load fit="cover" :src="detailData.avatar" />
            </div>
            <div class="u-name">
              {{ detailData.name }}
              <template v-if="detailData.gender==='Male' || detailData.gender==='Female'">
                <img v-if="detailData.gender==='Male'" class="icon-sex" src="@/assets/img/sex-man.png">
                <img v-if="detailData.gender==='Female'" class="icon-sex" src="@/assets/img/sex-woman.png">
              </template>
            </div>
            <div class="u-type">{{ clueCustomerTypeName || '--' }}</div>
          </div>
          <div class="u-content-box">
            <div class="u-tips">
              <span v-for="(l,i) in labelList" :key="i">{{ l.labelName }}</span>
            </div>
            <div class="u-cates">意向品类：{{ categorySelections || '--' }}</div>
            <div class="u-tel-source">
              <div>电话：{{ detailData.phone }}</div>
              <div>客户来源：{{ disCustomerSource || '--' }}</div>
            </div>
            <div>地址：{{ detailData.provinceName }}{{ detailData.cityName }}{{ detailData.districtsName }}{{ detailData.streetName }}{{ detailData.detailedAddress }}</div>
          </div>
        </div>
      </div>
      <div class="detail-menu-box" :class="{'fixed':menuFixed}" :style="menuStyl">
        <Scroll horizontal width="100%" class="d-menu-list">
          <div
            v-for="(item,i) in tabList"
            :key="i"
            :class="['d-menu',{'active':tabCode===item.code}]"
            @click.stop="handleClickNav(item)"
          >{{ item.name }}</div>
        </Scroll>
      </div>
    </div>
    <div class="detail-content-box" :class="{'ptd-top':menuFixed}">
      <component
        :is="activeComponent"
        v-if="detailData && detailData.id"
        ref="conComponent"
        :detail="detailData"
        :customer-pool-type="customerPoolType"
      />
    </div>
    <div v-if="detailData && detailData.id" class="detail-bottom-box">
      <div class="detail-bottom-content">
        <div class="icons">
          <div class="btn-icon" @click="handleTelphone">
            <img class="icon-tel" src="@/assets/img/icon-tel.png">
          </div>
          <div class="btn-icon" @click="handleSms">
            <img class="icon-msg" src="@/assets/img/icon-msg.png">
          </div>
          <!-- <div class="btn-icon" @click.stop="handleMenuChange('followUp')">
            <img class="icon-follow" src="@/assets/img/icon-follow.png">
          </div> -->
        </div>
        <div class="btns">
          <div
            v-for="(item,i) in outerBtns"
            :key="i"
            class="btn-text"
            @click.stop="handleMenuChange(item.optCode)"
          >
            {{ item.buttonName }}
          </div>
          <MoreBtn
            v-if="!(customerPoolType===0 && customerState===3) && moreBtns.length>0"
            class="btn-more"
            :opt-menu="moreBtns"
            @change="handleMenuChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ImageVideo from '@/components/ImageVideo'
import Scroll from '@/components/Scroll'
import MoreBtn from '../components/Item/MoreBtn'
import BrowseRecord from './components/BrowseRecord'
import FollowRecord from './components/FollowRecord'
import OptyRecord from './components/OptyRecord'
import OrderRecord from './components/OrderRecord'
import BasicInfo from './components/BasicInfo'
import { bus } from '@/utils/bus'
import { getDictByPatchType, getDictByType } from '@/apis/dataDict'
import { getDisDetail, queryByClueCustomerId } from '@/apis/customer'
export default {
  name: 'CustomerDetail',
  components: { ImageVideo, Scroll, MoreBtn },
  data() {
    return {
      isListen: false,
      barOpacity: 0, // 导航栏透明度
      topHeight: 0, // 顶部高度
      menuFixed: false,
      anchorId: this.$route.query.anchorId, // 锚点
      clueCustomerId: this.$route.query.id,
      customerPoolType: this.$route.query.type ? Number(this.$route.query.type) : '', // 来源客户池类型：0 公共客户池 ，潜客：1 ，意向客户：2
      detailData: '',
      tabCode: 'follow', // browse 当前页签
      tabList: [
        // { name: '浏览记录', code: 'browse', component: BrowseRecord },
        { name: '跟进记录', code: 'follow', component: FollowRecord },
        { name: '商机信息', code: 'opty', component: OptyRecord },
        { name: '订单信息', code: 'order', component: OrderRecord },
        { name: '基础信息', code: 'basic', component: BasicInfo }
      ],
      buttonList: [
        // outerType:指定外部操作的客户类型,moreType:指定更多操作的客户类型，customerState:指定客户状态
        { buttonName: '跟进', optCode: 'followUp', outerType: [0, 1, 2], url: '/customer/followUp/customer' }, // 外部按钮
        { buttonName: '分配导购', optCode: 'allocation', outerType: [0], /* moreType: [1, 2],*/ url: '/customer/allocation' },
        { buttonName: '转意向客户', optCode: 'turnIntention', outerType: [1], url: '/customer/turnIntention' },
        { buttonName: '收款', optCode: 'receipt', outerType: [2], url: '/customer/receipt' },

        { buttonName: '添加标签', optCode: 'addTag', moreType: [0, 1, 2], url: '/customer/addTag' },
        { buttonName: '客户流失', optCode: 'losing', moreType: [0], url: '/customer/losing' },
        { buttonName: '退回总部', optCode: 'sendBack', moreType: [0], customerState: [1], url: '/customer/sendBack' },
        { buttonName: '退回门店', optCode: 'sendBackShop', moreType: [1, 2], url: '/customer/sendBackShop' },
        { buttonName: '创建商机', optCode: 'opty', moreType: [2], url: '/customer/opty/create' }
        // { buttonName: '自投反馈', optCode: 'feedback', moreType: [0, 1, 2] ,url:'/customer/feedback'} // 自己创建的可操作
      ],
      dictData: {}, // 数据字典值
      labelList: [] // 标签
    }
  },
  computed: {
    headerBgColor() {
      return `rgba(22, 188, 131, ${this.barOpacity > 1 ? 1 : this.barOpacity})`
    },
    menuStyl() {
      const style = {}
      if (this.menuFixed) {
        style.top = `${this.topHeight}px`
      }
      return style
    },
    activeComponent() {
      return this.tabList.find(v => v.code === this.tabCode).component
    },
    // 公共客户池客户状态：待分配 1 ，已分配 2 ， 3 流失客户
    customerState() {
      const state = (this.detailData && this.detailData.customerState) || ''
      if (state === 'Failure' || state === 'Invalid') {
        // 客户状态为无效 Invalid 或 流失 Failure
        return 3
      }
      if (this.detailData && this.detailData.clueFollowUpUsers && this.detailData.clueFollowUpUsers.length >
      0) {
        // 跟进人存在则已分配
        return 2
      }
      return 1
    },
    positionCodes() {
      const t = this.$store.getters.userInfo
      return t.positionCodes || []
    },
    // 外部按钮
    outerBtns() {
      const btns = this.buttonList.filter(v => {
        return v.outerType && v.outerType.includes(this.customerPoolType)
      })

      if (this.customerPoolType === 0) {
        // 公共客户池
        // 只有设计主管 top_design_mg 岗位时，公共客户池 列表及对应的客户详情页，不展示 ‘分配’按钮、不展示‘更多-客户流失’ 按钮
        // 店长 top_shop_mg 、线上对接人 top_online_mg 、经理 top_dis  才有
        if (this.positionCodes.length === 1 && this.positionCodes[0] === 'top_design_mg') {
          return btns.filter(v => v.optCode !== 'allocation')
        }
      }
      return btns
    },
    // 更多按钮
    moreBtns() {
      const list = this.buttonList.filter(v => {
        let flag = v.moreType && v.moreType instanceof Array ? v.moreType.includes(this.customerPoolType) : false
        if (!flag) return false
        if (v.customerState || v.customerState instanceof Array) {
          flag = v.customerState.includes(this.customerState)
        }
        if (flag && v.optCode === 'sendBack') {
          // 退回总部条件：仅终端一级来源为线上，且是否自投为否的客户
          const { disCustomerFirstSource, isDisAdvertisement } = this.detailData
          return disCustomerFirstSource === 'Online' && ['0', 0].includes(isDisAdvertisement)
        }
        return flag
      })
      if ([1, '1'].includes(this.detailData.isDisAdvertisement)) {
        list.push({ buttonName: '自投反馈', optCode: 'feedback', url: '/customer/feedback' })
      }
      if (this.customerPoolType === 0) {
        // 公共客户池
        // 只有设计主管 top_design_mg 岗位时，公共客户池 列表及对应的客户详情页，不展示 ‘分配’按钮、不展示‘更多-客户流失’ 按钮
        // 店长 top_shop_mg 、线上对接人 top_online_mg 、经理 top_dis  才有
        if (this.positionCodes.length === 1 && this.positionCodes[0] === 'top_design_mg') {
          return list.filter(v => v.optCode !== 'losing')
        }
      }

      return list
    },
    clueCustomerTypeName() {
      // 客户类型：CRM_CUSTOMER_TYPE
      if (this.detailData && this.detailData.clueCustomerType) {
        const list = this.dictData['CRM_CUSTOMER_TYPE'] || []
        const o = list.find(v => v.dictCode === this.detailData.clueCustomerType)
        return o && o.dictName || ''
      }
      return ''
    },
    categorySelections() {
      // 意向品类：CRM_CATEGORY_SELECTION
      if (!(this.detailData && this.detailData.categorySelection)) {
        return ''
      }
      const tmpArr = this.detailData.categorySelection.split(',')
      const list = this.dictData['CRM_CATEGORY_SELECTION'] || []
      if (list.length === 0) return this.detailData.categorySelection
      const name = list.filter(l => {
        return tmpArr.some(v => v.toString() === l.dictCode.toString())
      }).map(v => v.dictName)
      return name.join(',')
    },
    // 客户来源
    disCustomerSource() {
      if (!(this.detailData && this.detailData.disCustomerFirstSource && this.detailData.disCustomerSecondSource)) {
        return ''
      }
      const fisrtList = this.dictData['DIS_CUSTOMER_PRIMARY_SOURCE'] || []
      const secondList = this.dictData['DIS_CUSTOMER_SECONDARY_SOURCE'] || []

      const disCustomerFirstSource = fisrtList.find(e => e.dictCode === this.detailData.disCustomerFirstSource)
      const disCustomerSecondSource = secondList.find(e => e.dictCode === this.detailData.disCustomerSecondSource)
      return `${disCustomerFirstSource ? disCustomerFirstSource.dictName : ''}-${disCustomerSecondSource ? disCustomerSecondSource.dictName : (this.detailData.disCustomerSecondSource || '')}`
    }
  },
  beforeRouteLeave(to, from, next) {
    // 判断退回首页，就删除keepAlive的缓存状态
    if (to.name === 'CustomerHome') {
      this.$removeKeepAliveCache(this)
    }
    next()
  },
  created() {
    bus.$on('refreshCustomerItem', ({ type, id }) => {
      /* if (id) {
        this.getDetail(id)
      } */
      this.refreshCustomerItem({ type, id })
    })
    /* window.refreshCustomerItem = () => {
      this.getDetail(this.$route.query.id)
    } */
    if (['opty', 'follow', 'order', 'basic'].includes(this.anchorId)) {
      // 'browse',
      this.tabCode = this.anchorId
    } else {
      this.tabCode = 'follow'// 'browse'
    }
    this.addEventListener()
    this.getDictData()
    this.getDetail(this.clueCustomerId)
    this.getLableList(this.clueCustomerId)
  },
  beforeDestroy() {
    this.removeEventListener()
  },
  activated() {
    this.addEventListener()
    this.getDetail(this.clueCustomerId)
  },
  deactivated() {
    this.removeEventListener()
  },
  methods: {
    addEventListener() {
      if (this.isListen) {
        return
      }
      this.isListen = true
      window.addEventListener('scroll', this.pageScroll, { passive: true })
    },
    removeEventListener() {
      if (!this.isListen) return
      this.isListen = false
      window.removeEventListener('scroll', this.pageScroll, { passive: true })
    },
    pageScroll(e) {
      const topEl = document.querySelector(`#oHeader`)
      if (topEl) {
        const top = topEl.getBoundingClientRect().top
        if (top >= 0) {
          this.barOpacity = 0
          this.menuFixed = false
          return
        }
        let barOpacity = 1 - (top + this.topHeight) / this.topHeight
        if (barOpacity > 1) barOpacity = 1
        this.barOpacity = barOpacity
      }

      let nHeight = 0
      const nEl = document.querySelector(`.detail-menu-box`)
      if (nEl) {
        nHeight = nEl.getBoundingClientRect().height
      }

      const conEl = document.querySelector(`.detail-content-box`)
      if (conEl) {
        const top = conEl.getBoundingClientRect().top
        this.menuFixed = top <= this.topHeight + nHeight
      }
    },
    getDetail(Id) {
      getDisDetail(Id).then(res => {
        this.detailData = res.data
      })
    },
    getLableList(Id) {
      queryByClueCustomerId(Id).then(res => {
        this.labelList = res.data || []
      })
    },
    async getDictData() {
      const dictTypeCodes = ['CRM_CATEGORY_SELECTION', 'CRM_CUSTOMER_TYPE', 'DIS_CUSTOMER_PRIMARY_SOURCE', 'DIS_CUSTOMER_SECONDARY_SOURCE']
      this.dictData = await getDictByPatchType({ dictTypeCodes })
    },

    handleHeadHeight(h) {
      this.topHeight = h
    },
    handleClickNav(d) {
      this.tabCode = d.code
      this.$nextTick(() => {
        this.pageScroll()
      })
    },
    // 拨打电话
    handleTelphone() {
      if (this.detailData.phone) {
        window.location.href = 'tel:' + this.detailData.phone
      } else {
        this.$toast('电话号码缺失')
      }
    },
    // 发短信 TODO:底座暂不支持
    handleSms() {
      const { phone } = this.detailData
      if (phone) {
        const u = navigator.userAgent
        const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
        const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
        let smsContent = `sms:${phone}?body=`
        if (isAndroid) {
          smsContent = `sms:${phone}?body=`
        } else if (isiOS) {
          smsContent = `sms:${phone}&body=`
        }
        window.location.href = smsContent
      } else {
        this.$toast('电话号码缺失')
      }
    },
    handleMenuChange(optCode) {
      const obj = [...this.buttonList, ...this.moreBtns].find(v => v.optCode === optCode)
      const path = obj && obj.url || ''
      if (path) {
        this.handleToPage(path)
      } else {
        this.$toast('操作异常!')
      }
    },
    handleToPage(path) {
      const { id, name, shopDeptCode, phone, disCode } = this.detailData
      const query = { id, name }
      if (path === '/customer/turnIntention' || path === '/customer/createopty') {
        if (path === '/customer/turnIntention') {
          const addrs = 'provinceCode cityCode districtsCode detailedAddress'.split(' ')
          if (addrs.some(e => !this.detailData[e])) {
            if (!phone) {
              this.$toast('联系电话和地址不完整,不允许转意向客户')
            } else {
              this.$toast('地址不完整,不允许转意向客户')
            }
            return
          }
          if (!phone) {
            this.$toast('联系电话为空,不允许转意向客户')
            return
          }
        }
        if (!shopDeptCode) {
          this.$toast('门店组织异常，无法操作')
          return
        }
        query.shopDeptCode = shopDeptCode
        query.disCode = disCode
      } else if (path === '/customer/allocation') {
        query.disCode = disCode
      } else if (path === '/customer/addTag') {
        query.source = this.customerPoolType === 0 ? 'commonpool' : 'mypool'
      }
      this.$router.push({
        path,
        query
      })
    },
    /**
     * @param {string} type 操作类型：edit 编辑，allocation 分配，follow 跟进 ， collection 收款， refund 退款 ，turnIntention 转意向客户 ， createOpty 创建商机 ，addTag 添加标签，sendBack 退回总部，sendBackShop 退回门店 ，losing 客户流失 , feedback 自投反馈
     * @param {String} id 线索客户Id
    */
    refreshCustomerItem({ type, id }) {
      if (type === 'losing') {
        // 客户流失：操作后刷新所选客户所在的列表页
        this.getDetail(id)
        return
      }
      if (type === 'addTag') {
        // 添加标签：操作后刷新所选客户上的‘标签’信息、最新跟进记录
        this.getLableList(id)
        if (this.tabCode === 'follow') {
          this.$refs.conComponent && this.$refs.conComponent.initData()
        }
      }
      if (type === 'sendBack') {
        // 退回总部：操作后刷新所选客户所在的列表页
        this.getDetail(id)
      }
      if (type === 'allocation') {
        // 分配: 操作后刷新所选客户所在的列表页
        this.getDetail(id)
      }
      if (type === 'collection') {
        // 收款：刷新客户的最新跟进记录
        if (this.tabCode === 'follow') {
          this.$refs.conComponent && this.$refs.conComponent.initData()
        }
      }
      if (type === 'sendBackShop') {
        // 退回门店：操作后刷新所选客户所在的列表页
        this.getDetail(id)
      }
      if (type === 'createOpty') {
        // 创建商机：刷新客户的最新跟进记录、商机信息页面
        if (['follow', 'opty'].includes(this.tabCode)) {
          this.$refs.conComponent && this.$refs.conComponent.initData()
        }
      }
      if (type === 'turnIntention') {
        // 转意向客户：操作后刷新所选客户所在的列表页
        this.getDetail(id)
      }
      if (type === 'follow') {
        // 跟进：操作新所选客户上的最新跟进记录
        if (this.tabCode === 'follow') {
          this.$refs.conComponent && this.$refs.conComponent.initData()
        }
      }
      if (type === 'edit') {
        // 编辑：刷新操作时所停留的列表页
        this.getDetail(id)
      }
    }
  }
}

</script>
<style lang='less' scoped>
.detail-headers{
  background-image: url(~@/assets/img/customer-detail-bg.png);
  background-repeat: no-repeat;
  background-size:  100% auto;
  border-radius: 0 0 6px 6px;
}
.detail-basic-box{
  padding: 30px 16px 14px;
  .basic-wrapper{
    padding: 16px;
    box-sizing: border-box;
    background: #FFFFFF;
    box-shadow: 0px 3px 30px 0px rgba(209,211,218,0.56);
    border-radius: 14px;
    .u-head{
      position: relative;
      padding-left: 78px;
      padding-bottom: 5px;
      min-height:30px;
      margin-bottom:14px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .u-avatar{
        position: absolute;
        left: 0;
        bottom: 0;
        z-index: 1;
        width: 68px;
        height: 68px;
        box-sizing: border-box;
        background: #FFFFFF;
        box-shadow: 0px 0px 30px 0px rgba(0,0,0,0.06);
        border-radius: 14px;
        border: 2px solid #FFFFFF;
        border-radius: 16px;
        overflow: hidden;
        /deep/.image-video{
          border-radius: 14px;
        }
      }
      .u-name{
        line-height: 25px;
        color: #343640;
        font-size: 18px;
        font-weight: bold;
        display: flex;
        align-items: center;
      }
      .icon-sex{
        width: 16px;
        height: 16px;
        margin-left: 6px;
      }
      .u-type{
        min-width: 61px;
        padding: 0 10px;
        height: 20px;
        line-height: 20px;
        box-sizing: border-box;
        background:rgba(238, 103, 26, 0.1);
        border-radius: 6px;
        color: #EE671A;
        font-size: 10px;
        font-weight: bold;
      }
    }
    .u-content-box{
      color: #979AA9;
      font-size: 12px;
      line-height: 18px;
      .u-tips{
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        margin-bottom: 6px;
        span{
          display: inline-block;
          padding: 0 6px;
          height: 20px;
          line-height: 18px;
          margin-right: 8px;
          margin-bottom: 6px;
          box-sizing: border-box;
          border-radius: 10px;
          border: 1px solid rgba(52, 54, 64,0.1);
          color: #7D8091;
          font-size: 10px;
          white-space: nowrap;
          &:last-child{
            margin-right: 0;
          }
        }
      }
      .u-cates{
        min-height: 18px;
      }
      .u-tel-source{
        margin-top: 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 4px;
      }
    }
  }
}
.detail-menu-box{
  position: relative;
  z-index:9;
  height: 46px;
  &.fixed{
    position: fixed;
    z-index: 9;
    top:66px;
    left: 0;
    width: calc(100vw);
    background: #50c9b3;
    border-radius: 0 0 6px 6px;
    overflow: hidden;
  }
  .d-menu-list{
    white-space: nowrap;
  }
  .d-menu{
    position: relative;
    display: inline-block;
    height: 46px;
    line-height: 46px;
    padding: 0 6px 0 16px;
    color: #FFFFFF;
    font-size: 16px;
    &:last-child{
      padding-right: 16px;
    }
    &.active{
      font-size: 18px;
      font-weight: bold;
      &::after{
        content: '';
        position: absolute;
        left: 50%;
        bottom: 6px;
        transform: translateX(-50%);
        width: 10px;
        height: 4px;
        background: #FFFFFF;
        border-radius: 2px;
      }
    }
  }
}
.detail-content-box.ptd-top{
  padding-top:46px;
}
.customer-detail-page{
  padding-bottom: 84px;
}
.detail-bottom-box{
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9;
  width: 100%;
  height: 84px;
  padding: 16px;
  box-sizing: border-box;
  background: #FFFFFF;
  .detail-bottom-content{
    padding-left: 12px;
    height: 52px;
    box-sizing: border-box;
    background: #FFFFFF;
    box-shadow: 0px 0px 30px 0px rgba(0,0,0,0.1);
    border-radius: 30px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content:space-between;
    .btn-icon{
      padding: 0 12px;
      height: 52px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .icon-tel{
      width: 20px;
      height: 20px;
    }
    .icon-msg{
      width: 20px;
      height: 20px;
    }
    .icon-follow{
      width: 22px;
      height: 22px;
    }
    .icons{
      // flex: 1;
      display: flex;
      justify-content:space-around;
    }
    .btns{
      display: flex;
      flex: 1;
    }
    .btn-text{
      display: inline-block;
      flex: 1;
      padding: 0 10px;
      height: 52px;
      line-height: 52px;
      background: rgba(22, 188, 131, 0.08);
      font-size: 14px;
      font-weight: bold;
      color: #16BC83;
      text-align: center;
      border-left: 1px solid #FFFFFF;
      white-space: nowrap;
    }
    .btn-more{
      flex: 1;
      display: inline-block;
      padding: 0 10px;
      height: 52px;
      line-height: 52px;
      border-radius: 0px 100px 100px 0px;
      font-size: 14px;
      font-weight: bold;
      color: #343640;
      text-align: center;
    }
  }
}
</style>
